package novel.front.novellist.test.thred;

public class ThreadLocalLx {

    private static final ThreadLocal<Object> threadLocal = new ThreadLocal<Object>(){
       @Override
       protected Object initialValue(){
           System.out.println("调用get方法时，当前线程共享变量没有设置，调用initialValue获取默认值！");
           return null;
       }
    };

    public static void main(String[] args) {
        new Thread(new MyIntegerTask("IntTask111")).start();
        new Thread(new MyStringTask("StringTask111")).start();
        new Thread(new MyIntegerTask("IntTask222")).start();
        new Thread(new MyStringTask("StringTask222")).start();

    }

    public static class MyIntegerTask implements Runnable{
        private String name;
        MyIntegerTask(String name){
            this.name = name ;
        }
        @Override
        public void run(){
            for (int i = 0; i < 5 ; i++) {
                if(null == ThreadLocalLx.threadLocal.get()){
                    ThreadLocalLx.threadLocal.set(0);
                    System.out.println("线程"+name+":0");
                }else {
                    int num = (Integer) ThreadLocalLx.threadLocal.get();
                    ThreadLocalLx.threadLocal.set(num+1);
                    System.out.println("线程"+name+":"+ThreadLocalLx.threadLocal.get());
                    if(i == 3){
                        ThreadLocalLx.threadLocal.remove();
                    }
                }
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static class MyStringTask implements Runnable{
        private String name;
        MyStringTask(String name){
            this.name = name;
        }
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                if(null == ThreadLocalLx.threadLocal.get()){
                    ThreadLocalLx.threadLocal.set("a");
                    System.out.println("线程"+name+":a");
                }else {
                    String str = (String)ThreadLocalLx.threadLocal.get();
                    ThreadLocalLx.threadLocal.set(str+"a");
                    System.out.println("线程"+name+":"+ThreadLocalLx.threadLocal.get());
                }
            }
            try{
                Thread.sleep(800);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
